package com.jiazhong.basic.atm.service.impl;

import com.jiazhong.basic.atm.bean.TradeLog;
import com.jiazhong.basic.atm.dao.CardDAO;
import com.jiazhong.basic.atm.dao.TradeLogDAO;
import com.jiazhong.basic.atm.service.CardService;

public class CardServiceImpl implements CardService {
    private CardDAO cdao;
    private TradeLogDAO tldao;

    public CardServiceImpl() {
        cdao = new CardDAO();
        tldao = new TradeLogDAO();
    }

    @Override
    public String transfer(String cardNo, String otherCardNo, double money) {
        // 1. 查询你的余额是否充足
        boolean isSufficient = cdao.isTheBalanceSufficient(cardNo, money);
        if (!isSufficient) {
            return cardNo + "余额不足";
        }
        // 2. 校验收款人账号是否存在
        boolean exists = cdao.isExists(otherCardNo);
        if (!exists) {
            return otherCardNo + "不存在";
        }
        // 3. 减钱
        cdao.update(cardNo, 0 - money);
        // 4. 加钱
        cdao.update(otherCardNo, money);
        // 5. 交易记录
        TradeLog tl = new TradeLog();
        tl.setCardId(cardNo);
        tl.setOtherCardId(otherCardNo);
        tl.setTradeMoney(money);
        tl.setTradeId(3);
        tldao.save(tl);
        return "交易成功！";
    }

    @Override
    public String cunkuan(String cardNo, double money) {
        // 1. 存款账号是否存在
        boolean exists = cdao.isExists(cardNo);
        if (!exists) {
            return cardNo + "卡号不存在";
        }
        // 2. 金额是否符合要求
        if (money <= 0) {
            return "金额不合法！";
        }
        // 2. 加钱
        cdao.update(cardNo, money);
        // 3. 交易记录
        TradeLog tl = new TradeLog();
        tl.setCardId(cardNo);
        tl.setTradeMoney(money);
        tl.setTradeId(1);
        tldao.save(tl);
        return "存款成功！";
    }
}
